package com.fau.wm.aop;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Hibernate;
import org.springframework.stereotype.Component;

import com.fau.wm.dao.IBaseDao;
import com.fau.wm.entity.MedicalAdmin;
import com.fau.wm.entity.MedicalCallCustomer;
import com.fau.wm.entity.MedicalCallCustomerHealth;
import com.fau.wm.entity.MedicalCallHealthSymptom;
import com.fau.wm.entity.MedicalMedicine;
import com.fau.wm.entity.MedicalMedicineSort;
import com.fau.wm.entity.MedicalOrdersProduct;
import com.fau.wm.entity.MedicalOrdersSign;
import com.fau.wm.entity.MedicalSsPerformance;
import com.fau.wm.entity.MedicalSsPurchase;
import com.fau.wm.util.SystemConfig;

/**
 * @desc 统计系统切面——会员购买力统计、员工业绩统计
 * @author dangjh
 * @datetime 2014年12月10日 下午9:44:19
 */
@Aspect
@Component
public class StatisticalSystemAop {

	@Resource
	private IBaseDao iBaseDao;
	
	@Pointcut("execution(* com.fau.wm.service.impl.OrdersManagerService.ordersSign(..))")
	private void ordersSign() {}
	
	@Pointcut("execution(* com.fau.wm.service.impl.OrdersManagerService.importSign(..))")
	private void importSign() {}
	
	/**
	 * @desc 保存业绩统计和会员购买力统计
	 * @param joinPoint
	 * @author dangjh
	 * @datetime 2014年12月10日 下午10:24:12
	 */
	@AfterReturning(value = "ordersSign()", returning = "returnValue")
	public void saveOrders(JoinPoint joinPoint, Map<String, Object> returnValue) {
		@SuppressWarnings("unchecked")
		List<MedicalOrdersSign> list = (List<MedicalOrdersSign>) returnValue.get("ordersSignList");
		// 保存员工业绩统计
		this.saveSsPerformance(list);
		
		// 保存会员群体统计
		this.saveSsPurchase(list);
		
	}
	
	/**
	 * @desc 导入订单-保存业绩统计和会员购买力统计
	 * @param joinPoint
	 * @author dangjh
	 * @datetime 2014年12月11日 上午11:57:46
	 */
	@AfterReturning(value = "importSign()",returning = "returnValue")
	public void saveImportOrders(JoinPoint joinPoint,Map<String, Object> returnValue) {
		@SuppressWarnings("unchecked")
		List<MedicalOrdersSign> list = (List<MedicalOrdersSign>) returnValue.get("ordersSignList");
		if(list.size() > 0) {
			// 保存员工业绩统计
			this.saveSsPerformance(list);
			
			// 保存会员群体统计
			this.saveSsPurchase(list);
		}
		
	}
	
	/**
	 * @desc 获得订单下的产品信息
	 * @param id
	 * @return List<MedicalOrdersProduct>
	 * @author dangjh
	 * @datetime 2014年12月10日 下午10:33:10
	 */
	@SuppressWarnings("unchecked")
	private List<MedicalOrdersProduct> findMedicineByOrderId(String id) {
		List<MedicalOrdersProduct> list = this.iBaseDao.getBySql("from MedicalOrdersProduct m where m.ordersId = ? ", null, id);
		return list;
	}
	
	/**
	 * @desc 查询客户病情
	 * @param id
	 * @return List<MedicalCallHealthArchive>
	 * @author dangjh
	 * @datetime 2014年12月10日 下午11:34:50
	 */
	@SuppressWarnings("unchecked")
	private List<MedicalCallCustomerHealth> findCustomerHealthById(String customerId) {
		List<MedicalCallCustomerHealth> list = this.iBaseDao.getBySql("from MedicalCallCustomerHealth m where m.customerId = ? ", null, customerId);
		return list;
	}
	
	/**
	 * @desc 保存员工业绩统计
	 * @author dangjh
	 * @datetime 2014年12月11日 上午11:52:26
	 */
	private void saveSsPerformance(List<MedicalOrdersSign> list) {
		for(MedicalOrdersSign sign : list) {
			MedicalSsPerformance performance = new MedicalSsPerformance();
			MedicalAdmin user = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, sign.getCusSerId());
			performance.setUserId(user.getId());
			performance.setUserName(user.getName());
			performance.setHospitalId(user.getEnterpriseId());
			if(!SystemConfig.SUPER_ADMIN.equals(user.getIsSuper())) {
				performance.setPlatformId(user.getGroup().getPlatform().getId());
				performance.setPlatformName(user.getGroup().getPlatform().getName());
				performance.setGroupId(user.getGroup().getId());
				performance.setGroupName(user.getGroup().getName());
			}
			
			performance.setOrderId(sign.getId());
			BigDecimal total = new BigDecimal(0);
			if(null != (sign.getPayment())) {
				total = total.add(sign.getPayment());
			}
			if(null != sign.getFreight()) {
				total = total.add(sign.getFreight());
			}
			performance.setOrderMoney(total);		// 货款 + 运费
			this.iBaseDao.saveObject(performance);
		}
	}
	
	/**
	 * @desc 保存会员群体统计
	 * @author dangjh
	 * @datetime 2014年12月11日 上午11:55:00
	 */
	private void saveSsPurchase(List<MedicalOrdersSign> list) {
		// 标准疾病表由健康档案信息中获得
		List<MedicalCallHealthSymptom> symList = new ArrayList<MedicalCallHealthSymptom>();
		
		// 根据产品信息获得药品类别（需去重）
		Set<MedicalMedicineSort> set = new HashSet<MedicalMedicineSort>();
				
		for(MedicalOrdersSign sign : list) {
			// 查找此次订单下的产品
			List<MedicalOrdersProduct> productList = this.findMedicineByOrderId(sign.getId());
			// 查找客户的健康档案信息
			List<MedicalCallCustomerHealth> healthList = this.findCustomerHealthById(sign.getCustomerId());
			
			// 根据产品信息获得药品类别信息
			for(MedicalOrdersProduct product : productList) {
				MedicalMedicine medicine = product.getMedicine();
				Hibernate.initialize(medicine.getMedicineSort());
				set.add(medicine.getMedicineSort());
			}
			
			// 从健康档案信息中得到  标准疾病信息
			for(MedicalCallCustomerHealth health : healthList) {
				MedicalCallHealthSymptom symptom = (MedicalCallHealthSymptom) this.iBaseDao.getObject(MedicalCallHealthSymptom.class, health.getHealthSymptom().getId());
				symList.add(symptom);
			}
		}
		
		Iterator<MedicalMedicineSort> iterator = set.iterator();
		if(symList.size() == 0) {
			for(MedicalOrdersSign sign : list) {
				while(iterator.hasNext()) {
					// 会员实体
					MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, sign.getCustomerId());
					MedicalMedicineSort sort = iterator.next();
					// 会员群体统计实体
					MedicalSsPurchase bean = new MedicalSsPurchase();
					bean.setName(customer.getName());
					bean.setAge(customer.getAge());
					bean.setSex(customer.getSex());
					bean.setLevel(customer.getCustomerLevel());
					bean.setPhoneNum(sign.getContactNo());
					bean.setOrdersDate(sign.getCreateTime());
					
					bean.setCityId(sign.getCity().getId());
					bean.setCityName(sign.getCity().getcName());
					BigDecimal total = new BigDecimal(0);
					if(null != (sign.getPayment())) {
						total = total.add(sign.getPayment());
					}
					if(null != sign.getFreight()) {
						total = total.add(sign.getFreight());
					}
					bean.setOrdersMoney(total);
					bean.setCustomerId(customer.getId());
					bean.setOrdersId(sign.getId());
					bean.setMedicineSortId(sort.getId());
					bean.setMedicineSort(sort.getName());
					bean.setHospitalId(sign.getHospitalId());
					this.iBaseDao.saveObject(bean);
				}
			}
		} else {
			for(MedicalOrdersSign sign : list) {
				for(MedicalCallHealthSymptom symptom : symList) {
					while(iterator.hasNext()) {
						// 会员实体
						MedicalCallCustomer customer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, sign.getCustomerId());
						MedicalMedicineSort sort = iterator.next();
						// 会员群体统计实体
						MedicalSsPurchase bean = new MedicalSsPurchase();
						bean.setName(customer.getName());
						bean.setAge(customer.getAge());
						bean.setSex(customer.getSex());
						bean.setLevel(customer.getCustomerLevel());
						bean.setPhoneNum(sign.getContactNo());
						bean.setOrdersDate(sign.getCreateTime());
						
						bean.setIllness(symptom.getId());
						bean.setCityId(sign.getCity().getId());
						bean.setCityName(sign.getCity().getcName());
						BigDecimal total = new BigDecimal(0);
						if(null != (sign.getPayment())) {
							total = total.add(sign.getPayment());
						}
						if(null != sign.getFreight()) {
							total = total.add(sign.getFreight());
						}
						bean.setOrdersMoney(total);
						bean.setCustomerId(customer.getId());
						bean.setOrdersId(sign.getId());
						bean.setMedicineSortId(sort.getId());
						bean.setMedicineSort(sort.getName());
						bean.setHospitalId(sign.getHospitalId());
						this.iBaseDao.saveObject(bean);
					}
				}
			}
		}
	}
	
}
